#ifndef __MESSAGECENTER_H__
#define __MESSAGECENTER_H__

/**
 * 
 */

#include "macros.h"
#include <mutex>
#include <map>
#include <list>
#include <thread>
#include <condition_variable>

class IMessage;
class IHandle;

class MESSAGECENTER_API MessageCenter
{
public:
    static MessageCenter* getInstance();

    ~MessageCenter();

public:
    // 绑定接收者，即队列添加接收者（相同类型）
    void attach(IHandle *pHandle);
    // 解绑定接收者
    void detach(IHandle *pHandle);

    // [同步] 发送消息
    bool sendMsg(const IMessage* pMsg);
    // [异步] 消息压入队列
    void pushMessgae(IMessage* pMsg, MessagePriority priority = MessagePriority::MP_COMMON);

private:
    MessageCenter();
    MessageCenter(const MessageCenter &other) = delete;
    MessageCenter &operator=(const MessageCenter &) = delete;

    // 消息队列线程函数
    void messageQueueThread();

private:
    static std::mutex                           m_mutex;
    static MessageCenter                        *m_instance;

    // 接收消息队列
    typedef std::list<IHandle*>                 Handles;
    typedef std::list<IMessage*>                Messages;
    typedef std::map<std::string, Handles*>     HMap;
    typedef std::condition_variable             CVar;
    HMap                                        m_handles;
    std::mutex                                  m_handleMutex;

    // 异步消息队列
    Messages                                    m_msgList;
    std::mutex                                  m_msgMutex;
    CVar                                        m_cv;
    bool                                        m_isMsgThreadRunning;
    std::thread                                 *m_msgThread;
};

#endif // __MESSAGECENTER_H__